package com.ruoyi.goods.server.imp;

import com.ruoyi.goods.excel.vo.GoodsVo;
import com.ruoyi.goods.server.GoodsExcelService;
import com.ruoyi.system.domain.GoodsCategory;
import com.ruoyi.system.domain.GoodsChoice;
import com.ruoyi.system.service.GoodsCategoryService;
import com.ruoyi.system.service.GoodsChoiceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class GoodsExcelServiceImp implements GoodsExcelService {

    @Autowired
    private GoodsChoiceService goodsChoiceService;
    @Autowired
    private GoodsCategoryService goodsCategoryService;

    /**
     * Excel 文件上传添加商品
     *
     * @param goodsVos excel 文件
     * @return
     */
    @Override
    public void uploadGoods(List<GoodsVo> goodsVos) {
        List<GoodsCategory> goodsCategories = goodsCategoryService.queryAllByLimit();
        List<GoodsChoice> collect = goodsVos.stream().map(goodsVoItem -> {
            List<GoodsCategory> categoryList = goodsCategories.stream().filter(item -> item.getId() == Integer.parseInt(goodsVoItem.getCategoryId())).collect(Collectors.toList());
            if (categoryList.size() == 0) return null;
            GoodsChoice goodsChoice = new GoodsChoice();
            BeanUtils.copyProperties(goodsVoItem, goodsChoice);
            // 获取头图
            String goodsUrl = goodsChoice.getGoodsUrl();
            Optional.ofNullable(goodsUrl)
                    .ifPresent(url -> goodsChoice.setImage(goodsChoiceService.getGoodsPic(goodsUrl)));
            double price = Double.parseDouble(goodsChoice.getPrice());
            //int indexOf = goodsChoice.getCommission().lastIndexOf("%");
            Double commission = Double.parseDouble(goodsChoice.getCommission().substring(0, goodsChoice.getCommission().length() - 1));
//            if (commission == -1)
            commission = 100 - commission;
            DecimalFormat df = new DecimalFormat("######0.00");
            double result = Double.parseDouble(commission + "") / 100;
            String formatPrice = df.format(price * result);
            goodsChoice
                    .setCategoryName(categoryList.get(0).getName())
                    .setStatus("0")
                    .setCommission(goodsChoice.getCommission().substring(0, goodsChoice.getCommission().length() - 1))
                    .setUserId(goodsVoItem.getShopDsr())
                    .setRemainNum(goodsChoice.getReceiveNum())
                    .setMinePrice(goodsVoItem.getPrice())
                    .setPrice(formatPrice)
                    .setSales("0");
            return goodsChoice;
        }).collect(Collectors.toList());
        goodsChoiceService.batchInsert(collect);
        System.out.println(collect);
    }
}
